//
//  PhoneInfoWidget.swift
//  PhoneInfoWidget
//
//  Created by 宋润理 on 2023/12/22.
//  Copyright © 2023 James. All rights reserved.
//

import WidgetKit
import SwiftUI

struct Provider: TimelineProvider {
    let words: [String] = ["路漫漫其修远兮，吾将上下而求索。",
                           "道阻且长，行则将至。",
                           "书山有路勤为径，学海无涯苦作舟。",
                           "天生我材必有用，千金散尽还复来。",
                           "如果你觉得委屈，觉得看不到光，那就成为光。"];
    func placeholder(in context: Context) -> SimpleEntry {
        
        SimpleEntry(date: Date(), emoji: self.words[Int(arc4random_uniform(5))])
    }

    func getSnapshot(in context: Context, completion: @escaping (SimpleEntry) -> ()) {
        let entry = SimpleEntry(date: Date(), emoji: self.words[Int(arc4random_uniform(5))])
        completion(entry)
    }

    func getTimeline(in context: Context, completion: @escaping (Timeline<Entry>) -> ()) {
        var entries: [SimpleEntry] = []
        let words: [String] = ["路漫漫其修远兮，吾将上下而求索。",
                               "道阻且长，行则将至。",
                               "书山有路勤为径，学海无涯苦作舟。",
                               "天生我材必有用，千金散尽还复来。",
                               "如果你觉得委屈，觉得看不到光，那就成为光。"];

        // Generate a timeline consisting of five entries an hour apart, starting from the current date.
        let currentDate = Date()
        for hourOffset in 0 ..< 5 {
            let word = words[hourOffset];
            let entryDate = Calendar.current.date(byAdding: .day, value: hourOffset, to: currentDate)!
            let entry = SimpleEntry(date: entryDate, emoji:word )
            entries.append(entry)
        }

        let timeline = Timeline(entries: entries, policy: .atEnd)
        completion(timeline)
    }
    
    
}

struct SimpleEntry: TimelineEntry {
    let date: Date
    let emoji: String
}

struct PhoneInfoWidgetEntryView : View {
    var entry: Provider.Entry
    var body: some View {
        VStack {
            Text("每日一句")
                .font(.title2)
                .foregroundColor(Color.gray)
            Spacer()
            Text(entry.emoji)
                .font(.footnote)
                .foregroundColor(Color.gray)
            Spacer()
            Text(entry.date, style: .time)
                .foregroundColor(Color.gray)
        }
    }
}

struct PhoneInfoWidget: Widget {
    let kind: String = "PhoneInfoWidget"

    var body: some WidgetConfiguration {
        StaticConfiguration(kind: kind, provider: Provider()) { entry in
            if #available(iOS 17.0, *) {
                PhoneInfoWidgetEntryView(entry: entry)
                    .containerBackground(.fill.tertiary, for: .widget)
            } else {
                PhoneInfoWidgetEntryView(entry: entry)
                    .padding()
                    .background()
            }
        }
        .configurationDisplayName("每日一句")
        .description("")
    }
}
